package fr.univ.lille1.server.daoimpl;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.ejb.Stateless;

import org.jboss.resteasy.util.Base64;

import fr.univ.lille1.server.dao.SessionKeyDao;
import fr.univ.lille1.server.domain.SessionKey;
import fr.univ.lille1.server.domain.User;

@Stateless
public class SessionKeyDaoImpl extends DaoImpl<Integer, SessionKey> implements SessionKeyDao{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1482521093523973005L;

	public SessionKey findSessionKeyByUser(User user) {
		List<SessionKey> list = list("SELECT s from SessionKey s WHERE s.user = ?1",user);
		if(list == null || list.size()==0){
			return null;
		}
		return list.get(0);
	}
	
	
	public SessionKey generateNewKey(User user) {
		long currentTime = System.currentTimeMillis();
		
		String key ="";
		KeyGenerator keyGen;
		try {
			keyGen = KeyGenerator.getInstance("AES");
			keyGen.init(256);
			SecretKey secretKey = keyGen.generateKey();
			key += Base64.encodeBytes(secretKey.getEncoded());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		

		SessionKey sessionKey = this.findSessionKeyByUser(user);
		if(sessionKey==null){
			sessionKey = new SessionKey();
			sessionKey.setUser(user);
			this.create(sessionKey);
		}
	      
		sessionKey.setSessionKey(key);
		sessionKey.setGenerateTime(currentTime);
		this.update(sessionKey);
		
		return sessionKey;
	}
}
